package rs.udd.service;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import rs.udd.model.Advert;
import rs.udd.model.Advertiser;
import rs.udd.model.Category;
import rs.udd.repository.AdvertRepository;
import rs.udd.repository.AdvertiserRepository;
import rs.udd.repository.CategoryRepository;
import rs.udd.service.dto.browse.BrowseDto;
import rs.udd.service.mappings.CategoryMapping;
import rs.udd.service.util.SecurityUtil;

@Service
@Transactional
public class BrowseServiceImpl implements BrowseService {

	@Resource
	private AdvertRepository advertRepository;
	
	@Resource
	private CategoryRepository categoryRepository;
	
	@Resource
	private AdvertiserRepository advertiserRepository;
	
	@Override
	public BrowseDto prepareBrowse() {
		List<Advert> adverts;
		List<Category> categories = categoryRepository.findAll();
		
		boolean isAdvertiserLogged = SecurityUtil.checkLoggedRole(Advertiser.class);
		if (isAdvertiserLogged) {
			Advertiser loggedAdvertiser = SecurityUtil.getLoggedUser(Advertiser.class);
			loggedAdvertiser = advertiserRepository.findOne(loggedAdvertiser.getId());
			
			Set<Advert> advertsByAdvertisers = loggedAdvertiser.getAdverts();
			adverts = new ArrayList<Advert>(advertsByAdvertisers);
			
			Set<Category> alteredCategories = new HashSet<Category>();
			for (Category category : categories) {
				Category alteredCategory = CategoryMapping.mapForBrowse(category);
				for (Advert advertisersAdvert : advertsByAdvertisers) {
					if (advertisersAdvert.getCategories().contains(category)) {
						alteredCategory.getAdverts().add(advertisersAdvert);
					}
				}
				alteredCategories.add(alteredCategory);
			}
			categories = new ArrayList<Category>(alteredCategories);
		} else {
			adverts = advertRepository.findAll();
		}
		
		for (Advert advert : adverts) {
			advert.getCategories().size();
		}
		
		for (Category category : categories) {
			category.getAdverts().size();
		}
		
		BrowseDto dto = new BrowseDto();
		dto.setAdverts(adverts);
		dto.setCategories(categories);
		
		return dto;
	}

}
